﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace BusinessLogic.Model.Repository.NewsItemRepositories
{
    class NewsItemRepository : Repository, INewsItemRepository
    {
        internal NewsItemRepository(BlogNETDataContext dataContext) : base(dataContext)
        {
        }

        public IQueryable<NewsItem> GetByTags(string tagParam)
        {
            if (tagParam != null && tagParam.Contains('|'))
            {
                string[] tagsToMatch = tagParam.Split('|');
                //prevent duplicate tags and reduce the number of tags
                //to prevent too much load on the SQL Server and eventual DoS attack
                tagsToMatch = tagsToMatch.Take(15).Distinct().ToArray();

                return from ni in DataContext.NewsItems
                       orderby ni.PostDate descending
                       where ni.Tags.Any<Tag>(t => tagsToMatch.Contains(t.TagValue))
                       select ni;
            }
            else if (tagParam != null && tagParam.Contains(' '))
            {
                string[] tagsToMatch = tagParam.Split(' ');
                tagsToMatch = tagsToMatch.Take(15).Distinct().ToArray();

                return from res in
                           (from tag in DataContext.Tags
                            where tagsToMatch.Contains(tag.TagValue)
                            group tag.NewsItem by tag.NewsItem into newsItems
                            select newsItems)
                       orderby res.Key.PostDate descending
                       where res.Count() == tagsToMatch.Length
                       select res.Key;
            }
            else
            {
                return from ni in DataContext.NewsItems
                       orderby ni.PostDate descending
                       where tagParam == null ? true :
                       ni.Tags.Any<Tag>(t => t.TagValue == tagParam)
                       select ni;
            }
        }


        public NewsItem Get(int newsItemID)
        {
            return (from ni in DataContext.NewsItems
                    where ni.NewsItemID == newsItemID
                    select ni).SingleOrDefault();
        }

        public byte[] GetImage(int newsItemID)
        {
            var image = (from ni in DataContext.NewsItems
                         where ni.NewsItemID == newsItemID
                         select ni.Image).SingleOrDefault();

            return image == null ? null : image.ToArray();
        }

        public void Delete(NewsItem newsItem)
        {
            DataContext.NewsItems.DeleteOnSubmit(newsItem);
            DataContext.SubmitChanges();
        }
    }
}
